package org.carabiner.infinitest;

import java.util.Enumeration;

import javax.swing.event.EventListenerList;

import junit.framework.Test;
import junit.framework.TestFailure;
import junit.framework.TestResult;
import junit.runner.BaseTestRunner;

class JUnitRunner extends BaseTestRunner implements TestRunner
{
  private EventListenerList listenerList;
  
  public JUnitRunner()
  {
    listenerList = new EventListenerList();
  }
  
  protected void runFailed(String arg0)
  {
    System.out.println("Run Failed " + arg0);    
  }

  public void testEnded(String arg0)
  {    
    System.out.println("Test Ended " + arg0);
  }

  public void testFailed(int arg0, Test test, Throwable arg2)
  {     
    System.out.println("Test Failed " + arg0 + test.toString());
  }

  public void testStarted(String arg0)
  {
    System.out.println("Test Started " + arg0);
  }
 
  public void runTest(String testClass)
  {
    Test suite = getTest(testClass);

    TestResult result = new TestResult();
    //result.addListener(this);
    suite.run(result);
    if (result.wasSuccessful())
    {
      fireTestSucceeded(testClass);
    }
    for(Enumeration<TestFailure> e = result.failures(); e.hasMoreElements();)
    {
      TestFailure failure = e.nextElement();
      fireTestFailed(testClass, failure.exceptionMessage(), failure.toString());
    }    
//    for(Enumeration<TestFailure> e = result.errors(); e.hasMoreElements();)
//    {
//      TestFailure failure = e.nextElement();
//      fireTestFailed(getClassName(failure), failure.exceptionMessage(), failure.toString());
//    }    
  }

  private String getClassName(TestFailure failure)
  {
    return failure.failedTest().getClass().getName();
  }

  public void addTestStatusListener(TestStatusListener listener)
  {
    listenerList.add(TestStatusListener.class, listener);    
  }
  
  
  protected void fireTestFailed(String testName, String message, String methodName)
  {
    TestStatusListener[] listeners = listenerList.getListeners(TestStatusListener.class);    
    for (int i = listeners.length - 1; i >= 0; i -= 1)
    {                  
      (listeners[i]).testFailed(new TestEvent(this, message, testName, methodName));      
    }
  }

  protected void fireTestSucceeded(String testName)
  {
    TestStatusListener[] listeners = listenerList.getListeners(TestStatusListener.class);    
    for (int i = listeners.length - 1; i >= 0; i -= 1)
    {                  
      (listeners[i]).testSucceeded(new TestEvent(this, "Test Succeeded", testName, ""));      
    }
  }
  
}
